const BaseRest = require('../rest.js');
module.exports = class extends BaseRest
{
    constructor(ctx)
    {
        super(ctx);
        this._CPInstance = this.model('apiv1/competition');
        this._service = this.service('apiv1/competition');
        this.cpModel=this.model('apiv1/competition');
        this.cpService=this.service('apiv1/competition');
        this.errNo = 0;
        this.errMsg = 'ok';
    }

    /**
     * 获取所有比赛&&获取指定比赛
     * @returns {Promise.<*>}
     */
    async getAction()
    {
        if (this._guid)
        {
            return this.end(await this._getCPByGuid());
        } else
        {
            return this.end(await this._getCP());
        }

    }

    /**
     * 即将废弃添加比赛v1 存在bug,显示所有的评委
     * @return {Promise} []
     */
    async postAction()
    {

        let postData = think.stringToJson(this.post('data'));
        if (postData === false)
        {
            return this.end(52004, '提交的表单信息错误,该数据必须为json格式,请检查数据格式,上传数据格式为{\'data\',yourJsonData},如 : $.post("http://127.0.0.1:8091/apiv1/competition",{\'data\':yourJsonData}),yourJsonData为你要上传的数据包');
        }

        let rdata = this._service.createCompetitionData(postData);

        if (rdata.isErr === false)
        {
            //获取提交的数据成功
            //存储数据库
            let dbRes = await this._service.saveData();
            if (dbRes.isErr !== true)
            {
                this.ctx.fail(dbRes.errNo, dbRes.errMsg, {cpGuid: dbRes.cpGuid});
                return false;
            } else
            {
                this.ctx.fail(dbRes.errNo, dbRes.errMsg);
                return true;
            }
        } else
        {
            //获取数据失败
            return this.ctx.fail(rdata.errNo, rdata.errMsg);

        }

    }

    /**
     * 添加比赛v1 修复第已版本的bug
     */
    async createCompetitionAction()
    {
        let cpdata = this.ctx.state.cpdata;
        this.createService = this.service('apiv1/createCompetitionV2');

        let rdata = this.createService.resolveData(cpdata);
        if (rdata.isErr === false)
        {
            let dbRes = await this.createService.addAllData();
            if (dbRes.isErr !== true)
            {
                this.ctx.fail(dbRes.errNo, dbRes.errMsg, {cpGuid: dbRes.cpGuid});
                return false;
            } else
            {
                this.ctx.fail(dbRes.errNo, dbRes.errMsg);
                return true;
            }
        } else
        {
            //获取数据失败
            return this.ctx.fail(rdata.errNo, rdata.errMsg);

        }


    }




    /**
     * 废弃 系统生成一个比赛的guid
     * @returns {Promise.<void>}
     */
    async createCPGuidAction()
    {
        let cpguid = think.uuid('v3');
        this.model('apiv1/competition').add({PK_CompetitionGuid: cpguid});
        return this.end({cpguid: cpguid});
    }

    /**
     * 删除比赛
     * @return {Promise} []
     */
    async deleteAction()
    {
        if (!this._guid)
        {
            return this.error(52015, '删除数据时guid不能为空,请检查参数')
        }
        let res = await this._CPInstance.where({'PK_CompetitionGuid': this._guid}).update({'IsDelete': "已删除"});

        if (res === 1)
        {
            return this.error(0, "删除成功");
        } else
        {
            return this.error(52016, "该比赛不存在,请检查guid");
        }
    }

    /**
     * 更新比赛 没写
     * @return {Promise} []
     */
    async putAction()
    {
        return this.success('.....');
    }

    /**
     * 获取指定比赛的作品数量
     * @returns {Promise.<*>}
     */
    async competitionWorksCountAction()
    {
        return this.success(await this._getCPWorksCountByWorksGuid());
    }

    /**
     * 比赛介绍
     * @returns {Promise.<void>}
     */
    async competitionDescAction()
    {
        let data = await  this._CPInstance.fieldReverse('FK_TeacherGuid,IsDelete').find(this._guid);
        return this.end(data);
    }

    /**
     * 比赛的所有流程
     * @returns {Promise.<*>}
     */
    async competitionStepAction()
    {
        let data = await this.model('apiv1/competitionSteps').where({FK_CompetitionGuid: this._guid}).select();
        return this.end(data);
    }

    /**
     * 根据比赛流程获取提交的作品数量和报名人数
     * @returns {Promise.<*>}
     */
    async competitionStepsWorksCountAndAppCountAction()
    {
        let workCount = await this.model('apiv1/competitionsteptoworks').getWorksCountByWorkStepsGuid(this._guid);
        let applicationCount = await this.model('apiv1/application').getApplicationCountByGuid(this._guid);
        let data = {
            worksCount: workCount,
            applicationCount: applicationCount
        };
        return this.end(data);
    }

    /**
     * 比赛步骤信息
     * @returns {Promise.<*>}
     */
    async getStepInfoByGuidAction()
    {
        let data = await this.model('apiv1/competitionSteps').find(this._guid);
        return this.end(data);
    }


    /**
     * 获取全部比赛
     * @returns {Promise.<{nowCompetition: {total: *, items: *}, oldCompetition: {total: *, items: *}}>}
     * @private
     */
    async _getCP()
    {
        this.finishedTotal = await this._CPInstance.getFinishedTotal();
        this.nowItems = await this._CPInstance.getNowItems();
        this.finishedItems = await  this._CPInstance.getFinishedItems();
        this.nowTotal = await this._CPInstance.getNowTotal();
        return {
            'nowCompetition': {
                'total': this.nowTotal,
                'items': this.nowItems
            },
            'oldCompetition': {
                'total': this.finishedTotal,
                'items': this.finishedItems
            }
        };
    }

    /**
     * 获取指定作品数量
     * @returns {Promise.<{worksTotal: *}>}
     * @private
     */
    async _getCPWorksCountByWorksGuid()
    {
        let count = await this.cpService.getCPWorksCountByWorksGuid(this._guid);
        let res = count ? count : 0;
        return {
            'worksTotal': count
        }
    }

    /**
     * 根据guid获取比赛信息
     * @returns {Promise.<void>}
     * @private
     */
    async _getCPByGuid()
    {
        return await this._CPInstance.getCPByGuid(this._guid);
    }

    /**
     * 进入当前流程
     * @returns {Promise.<void>}
     */
    async entercurrentstAction()
    {
        let data = this.ctx.state.data;
        let re = await  this._CPInstance.where({PK_CompetitionGuid: data.cpguid}).update({FK_NowStepsGuid: data.stguid});
        return this.infoDbUpdate(re);
    }


    /**
     * 结束当前比赛
     * @returns {Promise.<*>}
     */
    async endCurrentCPAction()
    {
        let res = await this._CPInstance.where({PK_CompetitionGuid: this._guid}).update({
            Status: '已结束',
            FK_NowStepsGuid: 'null'
        });
        return this.infoDbUpdate(res);
    }

    /**
     * 暂停当前比赛
     * @returns {Promise.<*>}
     */
    async pauseCurrentCP()
    {
        let res = await this._CPInstance.where({PK_CompetitionGuid: this._guid}).update({Status: '暂停中'});
        return this.infoDbUpdate(res);
    }


    async updatecpbasicAction(){
        //数据验证
        let postData=think.stringToJson(this.post('data'));
        if(postData===false){
            return this.responseInfo(52004, '提交的表单信息错误,该数据必须为json格式,请检查数据格式,上传数据格式为{\'data\',yourJsonData},如 : $.post("http://127.0.0.1:8091/apiv1/competition",{\'data\':yourJsonData}),yourJsonData为你要上传的数据包');
        }
        let baseRules={
            cpguid:{type:'string'},
            Title: { type: "string",min:1},
            CoverUrl: { type: "string",min:5},
            Desc: { type: "string",min:1},
            GameShowsType: { type:'string',enum:['本平台发布','第三方页面']},
            GameStartTime: { type: "number"},
            GameEndTime: { type: "number"},
        };
        let bbase=think.validate(postData,baseRules);
        if(bbase!==true)return this.error(52040,bbase[0].message);

        //postData为验证成功后的数据

        //获取比赛的guid
        let cpguid=postData.cpguid;

        return this.resopnseUpdate(await this.cpModel.where({PK_CompetitionGuid:cpguid}).update(postData));

    }


    async updatecpsettingAction(){
        //数据验证
        let postData=think.stringToJson(this.post('data'));
        if(postData===false){
            return this.responseInfo(52004, '提交的表单信息错误,该数据必须为json格式,请检查数据格式,上传数据格式为{\'data\',yourJsonData},如 : $.post("http://127.0.0.1:8091/apiv1/competition",{\'data\':yourJsonData}),yourJsonData为你要上传的数据包');
        }
        let baseRules={
            cpguid:{type:'string'},
            HeadCount: { type: "number",min:1},
            ApplyNotes: { type: "string",min:1},
            ApplyStartTime: { type: "number",min:1},
            ApplyEndTime: { type: "number",min:1},
            ApplyType: { type: "string",enum:['团队','个人']},
        };
        let bbase=think.validate(postData,baseRules);
        if(bbase!==true)return this.error(52040,bbase[0].message);

        //postData为验证成功后的数据

        //获取比赛的guid
        let cpguid=postData.cpguid;

        return this.resopnseUpdate(await this.cpModel.where({PK_CompetitionGuid:cpguid}).update(postData));

    }






};
